package com.yunban.project.api.text_check.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunban.project.api.text_check.domain.CorrectionConfig;
import com.yunban.project.api.text_check.domain.CorrectionDict;
import com.yunban.project.api.text_check.dto.CorrectionDictReq;
import com.yunban.project.api.text_check.dto.CorrectionDictResp;
import com.yunban.project.api.text_check.enums.CorrectionModel;
import com.yunban.project.api.text_check.mapper.CorrectionDictMapper;
import com.yunban.project.api.text_check.service.CorrectionConfigService;
import com.yunban.project.api.text_check.service.CorrectionDictService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.EventEnum;
import net.lab1024.sa.base.common.domain.PageParam;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.common.exception.BusinessException;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: lijiajun
 * @date: 2024-11-21
 * @version: 1.0
 */
@Slf4j
@Service
public class CorrectionDictServiceImpl extends ServiceImpl<CorrectionDictMapper, CorrectionDict> implements CorrectionDictService {

    @Resource
    private CorrectionConfigService correctionConfigService;

    // 检查 errorWord 是否存在,如果存在，则不需要添加
    public void checkErrorWord(String errorWord, Long id) {
        LambdaQueryWrapper<CorrectionDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CorrectionDict::getErrorWord, errorWord);
        CorrectionDict dict = this.getOne(wrapper, false);
        if (0 == id || ObjectUtils.isEmpty(id)) {
            if (!ObjectUtils.isEmpty(dict)) {
                throw new BusinessException("该错误词已存在");
            }
        } else {
            if (!ObjectUtils.isEmpty(dict) && !dict.getId().equals(id)) {
                throw new BusinessException("该错误词已存在");
            }
        }

    }

    @Override
    public PageResult<CorrectionDictResp> getDictList(PageParam req) {
        LambdaQueryWrapper<CorrectionDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CorrectionDict::isEnabled, true);
        Page<CorrectionDict> paged = this.page(SmartPageUtil.convert2PageQuery(req), wrapper);
        return SmartPageUtil.convert2PageResult(paged, CorrectionDictResp.class);
    }

    @Override
    public Boolean saveDict(CorrectionDictReq req) {
        if (!StringUtils.hasText(req.getCorrectWord())) {
            throw new BusinessException("正确词不能为空");
        }
        if (!StringUtils.hasText(req.getErrorWord())) {
            throw new BusinessException("正确词不能为空");
        }
        // 检查错词库是否存在
        this.checkErrorWord(req.getErrorWord(), 0L);
        CorrectionDict dict = new CorrectionDict();
        BeanUtils.copyProperties(req, dict);
        return this.save(dict);
    }

    @Override
    public Boolean updateDict(long id, CorrectionDictReq req) {
        // 检查错词库是否存在
        this.checkErrorWord(req.getErrorWord(), id);
        CorrectionDict dict = this.getById(id);
        if (ObjectUtils.isEmpty(dict)) {
            throw new BusinessException("该词典已被删除");
        }
        BeanUtils.copyProperties(req, dict);
        return this.updateById(dict);
    }

    @Override
    public Boolean updateDictEnabled(Long id, EventEnum event) {
        CorrectionDict dict = this.getById(id);
        if (ObjectUtils.isEmpty(dict)) {
            throw new BusinessException("该词典已被删除");
        }
        dict.setEnabled(event.equals(EventEnum.enable));
        return this.updateById(dict);
    }

    public static void main(String[] args) {
        String word = "区就促中心培训条线负责人详细解读了【**】年培训工作指标及补贴政策，并对各机构部署了【**】年重点任务，强调需结合区域发展需求，优化培训资源配置。";
        List<CorrectionDict> words = new ArrayList<>();
        CorrectionDict dict = new CorrectionDict();
        dict.setCorrectWord("2025");
        dict.setPlaceholder("【**】");
        dict.setErrorWord("2025");
        words.add(dict);
        for (CorrectionDict r : words) {
//            word = word.replace(r.getErrorWord(), r.getPlaceholder());
            // 替换敏感词
            String placeWordStr = String.format("<error-text :%s>%s</error-text>", r.getErrorWord(), r.getCorrectWord());
            word = word.replace(r.getPlaceholder(), placeWordStr);
        }
        System.out.println(word);
    }

    @Override
    public String sensitiveWordPlace(String word, boolean hasRestore) {
        // 获取可以进行占位的词
        LambdaQueryWrapper<CorrectionDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNotNull(CorrectionDict::getPlaceholder);
        wrapper.eq(CorrectionDict::isHasSensitiveWord, true);
        List<CorrectionDict> words = this.list(wrapper);
        log.info("words:{}", JSON.toJSONString(words));
        // 【某】今天来到了上海省
        for (CorrectionDict dict : words) {
            // 如果匹配上了，则使用占位符替代
            if (StringUtils.hasText(dict.getPlaceholder())) {
                if (!hasRestore) {
                    word = word.replace(dict.getErrorWord(), dict.getPlaceholder());
                } else {
                    // 替换敏感词
                    String placeWordStr = String.format("<error-text :%s>%s</error-text>", dict.getErrorWord(), dict.getCorrectWord());
                    word = word.replace(dict.getPlaceholder(), placeWordStr);
                }
            }
        }
        return word;
    }

    @Override
    public String localWordPlace(String text) {
        if (!StringUtils.hasText(text)) {
            return text;
        }
        // 查看本地词典配置是否开启
        CorrectionConfig config = this.correctionConfigService.findByCode(CorrectionModel.LOCAL);
        // 如果本地词典未开启，则直接返回
        if (ObjectUtils.isEmpty(config) || !config.isEnabled()) {
            return text;
        }
        // 如果开启了本地词库配置，那么排除掉敏感词后，进行纠错
        LambdaQueryWrapper<CorrectionDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CorrectionDict::isHasSensitiveWord, false);
        List<CorrectionDict> dictList = this.list(wrapper);
        for (CorrectionDict dict : dictList) {
            // 词库中错误文本于正确文本必须存在才可以进行替换，否则直接跳过
            if (!StringUtils.hasText(dict.getErrorWord()) || !StringUtils.hasText(dict.getCorrectWord())) {
                continue;
            }
            // 替换正确的词
            String placeWordStr = String.format("<error-text :%s>%s</error-text>", dict.getErrorWord(), dict.getCorrectWord());
            text = text.replace(dict.getErrorWord(), placeWordStr);
        }
        return text;
    }
}